<script setup lang="ts">
import { useToast } from 'nutui-uniapp/composables'
import { reactive, ref } from 'vue'
import { sendUserLoginSms } from '@/api/access'
import { useUserStore } from '@/stores/user'
import { checkRules } from '../rules'

// 外部参数
const props = defineProps({
  // 是否显示版权信息
  showCopyright: {
    type: Boolean,
    default: true,
  },
})

const toast = useToast()

// 用户存储
const userStore = useUserStore()

// 状态参数
const state = reactive({
  // 页面类型（phone、account、verify、register）
  pageType: 'phone',
  // 验证码重试倒计时
  smsRetryTimes: 0,
  // 版权信息
  copyright: '© 2025 xxx 版权所有',
})

// 表单
const formData = ref({
  phone: '',
  code: '',
  passport: '',
  password: '',
})

// 切换页面类型
function changeLoginType(type: string) {
  state.pageType = type
}

// 模拟发送短信
async function handleSendCode() {
  if (state.smsRetryTimes > 0) {
    state.pageType = 'verify'
    return false
  }
  try {
    checkRules(['phone'], formData)
    toast.loading('正在发送')
    state.smsRetryTimes = 60
    const timer = setInterval(() => {
      if (state.smsRetryTimes > 0) {
        state.smsRetryTimes--
      }
      else {
        clearInterval(timer)
      }
    }, 1000)
    await sendUserLoginSms({
      phone: formData.value.phone,
    })
    toast.success('验证码已发送')
    state.pageType = 'verify'
  }
  catch (e: any) {
    toast.error(e.message, {
      duration: 1000,
    })
  }
}

// 注册
async function handleReg() {
  checkRules(['phone', 'code', 'passport', 'password'], formData)
  toast.loading('请稍候')
  setTimeout(() => {
    toast.success('模拟注册成功', {
      duration: 1000,
      onClose: () => {
        state.pageType = 'phone'
      },
    })
  }, 1000)
}

// 登录
async function handleLogin() {
  try {
    if (state.pageType === 'phone' || state.pageType === 'verify') {
      checkRules(['phone', 'code'], formData)
      toast.loading('请稍候')
      // 手机登录
      await userStore.loginByPhone(formData.value.phone, formData.value.code)
    }
    else {
      checkRules(['passport', 'password'], formData)
      toast.loading('请稍候')
      // 账号登录
      await userStore.loginByAccount(formData.value.passport, formData.value.password)
    }
    // 登录成功跳转
    // 如果使用isLogin + 组件引入的话，后面的代码不会运行
    toast.success('登录成功', {
      duration: 1000,
      onClose: () => {
        uni.switchTab({
          url: '/pages/mine/index',
        })
      },
    })
  }
  catch (e: any) {
    toast.error(e.message, {
      duration: 1000,
    })
  }
}
</script>

<template>
  <view>
    <nut-toast />
    <template v-if="state.pageType === 'verify'">
      <view class="board">
        <view class="title">
          请输入验证码
          <br>
          <view class="tips">
            已发送至 {{ formData.phone }}
          </view>
        </view>
      </view>
      <view class="login-view">
        <view class="content">
          <view class="form">
            <view class="form-line">
              <nut-code-input v-model="formData.code" :size="40" />
            </view>
            <view class="buttons">
              <nut-button size="large" type="info" @click="handleLogin">
                确认
              </nut-button>
              <view class="mt-30rpx">
                <nut-button
                  size="large"
                  type="info"
                  plain
                  :disabled="!!state.smsRetryTimes"
                  @click="handleSendCode"
                >
                  {{ state.smsRetryTimes ? `${state.smsRetryTimes}秒后重试` : '获取验证码' }}
                </nut-button>
              </view>
            </view>
            <view class="action-type">
              <view @click="changeLoginType('phone')">
                更换手机
              </view>
              <view @click="changeLoginType('account')">
                账号登录
              </view>
            </view>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <view class="board">
        <view class="title">
          您好，
          <br>
          欢迎使用本系统
        </view>
      </view>
      <view class="login-view">
        <view class="content">
          <view class="form">
            <view v-if="state.pageType !== 'account'" class="form-line">
              <view class="input">
                <nut-input
                  v-model="formData.phone"
                  class="!p-0"
                  placeholder="请输入手机号"
                  clearable
                />
              </view>
            </view>
            <template v-if="state.pageType !== 'phone'">
              <view class="form-line">
                <view class="input">
                  <nut-input
                    v-model="formData.passport"
                    class="!p-0"
                    placeholder="请输入登录账号"
                    clearable
                  />
                </view>
              </view>
              <view class="form-line">
                <view class="input">
                  <nut-input
                    v-model="formData.password"
                    class="!p-0"
                    type="password"
                    placeholder="请输入登录密码"
                    clearable
                  />
                </view>
              </view>
            </template>
            <view v-if="state.pageType === 'phone'" class="buttons">
              <nut-button size="large" type="info" @click="handleSendCode">
                获取验证码
              </nut-button>
            </view>
            <view v-else-if="state.pageType === 'account'">
              <nut-button size="large" type="info" @click="handleLogin">
                登录
              </nut-button>
            </view>
            <view v-else-if="state.pageType === 'register'" class="buttons">
              <nut-button size="large" type="info" @click="handleReg">
                注册
              </nut-button>
              <view class="mt-30rpx">
                <nut-button size="large" type="info" plain @click="changeLoginType('phone')">
                  登录
                </nut-button>
              </view>
            </view>
            <view v-if="state.pageType !== 'register'" class="action-type">
              <view @click="changeLoginType(state.pageType === 'phone' ? 'account' : 'phone')">
                {{ state.pageType === 'phone' ? '账号登录' : '手机登录' }}
              </view>
              <view @click="changeLoginType('register')">
                注册
              </view>
            </view>
          </view>
        </view>
      </view>
    </template>
    <text v-if="props.showCopyright && state.copyright" class="copyright">
      {{ state.copyright }}
    </text>
  </view>
</template>

<style lang="scss" scoped>
.board {
  width: 100%;
  height: 350rpx;

  .title {
    transform-origin: left;
    font-size: 42rpx;
    padding: 130rpx 0 0 60rpx;
    font-weight: bold;
    line-height: 70rpx;

    .tips {
      font-weight: normal;
      color: #999;
      font-size: 28rpx;
      line-height: 60rpx;
    }
  }
}

.login-view {
  width: 100%;
  position: relative;

  .content {
    margin: 0 60rpx;
    font-size: 28rpx;
    padding-bottom: 40rpx;

    .uni-input-placeholder {
      color: #aeaeae;
    }

    .form {
      .form-line {
        position: relative;

        .input {
          display: flex;
          height: 90rpx;
          line-height: 90rpx;
          margin-bottom: 40rpx;
          border-bottom: 1px solid #e9e9e9;
          font-size: 28rpx;

          .uni-input {
            padding: 0;
          }
        }
      }

      .buttons {
        margin-top: 80rpx;
      }

      .action-type {
        display: flex;
        justify-content: space-between;
        font-size: 26rpx;
        color: #666;
        padding: 20rpx 0 0;

        > * {
          padding: 20rpx;
        }
      }
    }
  }
}

.copyright {
  position: absolute;
  z-index: 2;
  right: 0;
  bottom: 0;
  transform-origin: right;
  font-size: 24rpx;
  color: #666;
  padding: 20rpx;
}
</style>
